<template>
  <div class="employees">
    <headTool>
      <span slot="before">总有{{ formInfo.total }}条记录</span>
      <div slot="after">
        <el-button @click="exportHardExcel" type="warning" size="small"
          >复杂导出</el-button
        >
        <el-button @click="exportTitleExcel" type="warning" size="small"
          >导出表头</el-button
        >
        <el-button @click="exportExcel" type="success" size="small"
          >导出</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="$router.push({ path: '/import', query: { type: 'emp' } })"
          >导入</el-button
        >
        <el-button type="primary" size="small" @click="showDialog = true"
          >新增员工</el-button
        >
      </div>
    </headTool>

    <el-card class="box-cardBottom">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="120">
        </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column label="头像">
          <!-- prop="province" -->
          <template slot-scope="{ row }">
            <img
              :src="row.staffPhoto"
              v-imgerror="imgDefault"
              alt=""
              style="width: 60px"
              @click="showQrCode(row.staffPhoto)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          width="120px"
        ></el-table-column>
        <el-table-column prop="workNumber" label="工号"> </el-table-column>
        <!-- prop="formOfEmployment" -->
        <el-table-column label="聘用形式">
          <template slot-scope="{ row }">
            {{ row.formOfEmployment | hireTypeVal }}
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门"> </el-table-column>
        <el-table-column label="入职时间" width="120px">
          <template slot-scope="{ row }">
            {{ row.timeOfEntry | formatDate() }}
          </template>
        </el-table-column>
        <!-- prop="enableState" -->
        <el-table-column label="状态">
          <template slot-scope="{ row }">
            <el-switch
              v-model="row.enableState"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="转正时间" width="120px">
          <template slot-scope="{ row }">
            {{ row.correctionTime | formatDate() }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="230px">
          <template slot-scope="{ row }">
            <el-button
              @click="
                $router.push({
                  path: '/employees/detail',
                  query: { id: row.id },
                })
              "
              type="text"
              size="small"
              >查看</el-button
            >
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >转正</el-button
            >
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >调岗</el-button
            >
            <el-button @click="handleClick(scope.row)" type="text" size="small"
              >离职</el-button
            >
            <el-button @click="roleClick(row.id)" type="text" size="small"
              >角色</el-button
            >
            <el-button @click="delBtn(row.id)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="getEmployeesList"
        :current-page.sync="formInfo.page"
        :page-size="formInfo.size"
        layout="total, prev, pager, next"
        :total="formInfo.total"
      >
      </el-pagination>
      <addDepts
        :dialogFormVisible.sync="showDialog"
        @getEmployeesList="getEmployeesList"
        :formInfo="formInfo"
      ></addDepts>

      <!-- 添加弹出框 -->
      <el-dialog :visible.sync="showCodeDialog" title="二维码">
        <el-row type="flex" justify="center">
          <!-- 二维码 -->
          <canvas ref="canvas"></canvas>
        </el-row>
      </el-dialog>

      <!-- 角色弹框 -->
      <roleSetting
        :isShowRole.sync="isShowRole"
        :currentId="currentId"
        ref="roleSet"
      ></roleSetting>
    </el-card>
  </div>
</template>

<script>
import { getEmployeesList, delEmp } from "@/api/employees";
//导入封装好的类型转换的对象
import constant from "@/api/constant/employees";
import addDepts from "./components/add-depts.vue";
// 导入处理日期的函数
import { formatDate } from "@/filters";
import QrCode from "qrcode";
import roleSetting from "./components/role-setting";
export default {
  name: "employees",
  data() {
    return {
      //设置id
      currentId: "",
      //是否显示角色弹框
      isShowRole: false,
      //是否显示弹出框
      showCodeDialog: false,
      //聘用形式做判断
      hireType: constant.hireType,
      //表格数据
      tableData: [],
      //分页数据
      formInfo: {
        page: 1, //页码
        size: 10, //页容量
        total: 100, //数据列表总数
      },
      showDialog: false,
      imgDefault: require("@/assets/common/bigUserHeader.png"),
    };
  },
  components: {
    addDepts,
    roleSetting,
  },
  created() {
    this.getEmployeesList();
  },
  methods: {
    //点击图片触发的事件
    showQrCode(url) {
      if (url) {
        //显示弹框
        this.showCodeDialog = true;
        //为true的时候还没有渲染DOM,所以就以为这里面还没有canvas标签,需要等到dom渲染了再来找canvas变迁,并把它画成二维码
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.canvas, url);
        });
      } else {
        this.$message.error("该员工没有图片");
      }
    },
    //第一种方法直接调用获取员工列表,然后传入页容量和当前的页数,获取数据,
    //第二种不传参数:方法直接获取所有数据,然后传入当前的页数来进行跳转获取数据
    async getEmployeesList() {
      let res = await getEmployeesList(this.formInfo);
      //   console.log(res);
      this.formInfo.total = res.data.total;

      this.tableData = res.data.rows;
      //判断状态是否为1,如果为1就是true,否则就是false
      this.tableData.enableState = res.data.rows.forEach((item) => {
        if (item.enableState == 1) {
          item.enableState = true;
        } else {
          item.enableState = false;
        }
      });
      //   console.log(res);
    },

    //删除功能
    async delBtn(id) {
      await this.$confirm("确定要删除此员工的信息吗?", "温馨提示");
      await delEmp(id);
      this.$message.error("删除此员工成功");
      /**在第一页,中间页,最后一页删除之后的
       *如果是第一页还是获取第一页的数据,
       *中间页也是获取的中间页的数据,
       *但是如果是最后一页,需要判断一下如果最后一页是第一页,当没有数据的时候需要显示没有数据
       */
      this.formInfo.total = this.formInfo.total - 1;
      //   let pageList = Math.ceil(this.formInfo.total / this.formInfo.size);
      //   if (this.formInfo.page < pageList) {
      //     await this.getEmployeesList();
      //   } else {
      //     if (pageList <= this.formInfo.size) {
      //       this.formInfo.page = pageList < 1 ? "1" : pageList;
      //     }
      //   }
      //   await this.getEmployeesList({ page: pageList });
      this.getEmployeesList();
    },

    //导出所有数据
    async exportExcel() {
      //1-需要请求到所有员工的数据
      let res = await getEmployeesList({
        page: 1,
        size: this.formInfo.total,
      });
      //获取到所有员工的数据保存到list中
      let list = res.data.rows;
      //设置表头数据
      const headers = {
        序号: "no",
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      //遍历传所有的中文表头
      let keys = Object.keys(headers);
      console.log(keys); // ["手机号", "姓名", "入职日期", "聘用形式", "转正日期", "工号", "部门"]

      let bigArr = list.map((item, index) => {
        // item是每个元素，又是一个对象，要遍历转成数组
        let arr = [];

        for (let key in headers) {
          //先根据中文的key,取出对应的英文的key
          let engKey = headers[key];

          //   arr.push(index);
          if (key == "入职日期" || key == "转正日期") {
            let res = formatDate(item[engKey]);
            arr.push(res);
          } else if (key == "聘用形式") {
            let str = item[engKey] == 1 ? "正式" : "未知";
            arr.push(str);
          } else if (key == "序号") {
            arr.push(item[index]);
          } else {
            arr.push(item[engKey]);
          }
        }
        return arr;
      });
      console.log(bigArr);
      // 懒加载使用插件的办法
      // 哪里要用，就在哪里导入插件对应的js
      // 导入成功就调用.then
      import("@/vendor/Export2Excel").then((excel) => {
        //这个插件里写了这个方法才能用
        excel.export_json_to_excel({
          header: keys, //表头
          //数据
          data: bigArr,
          filename: "员工列表",
        });
      });
    },
    //导出表头
    exportTitleExcel() {
      import("@/vendor/Export2Excel").then((excel) => {
        excel.export_json_to_excel({
          //表头
          header: ["手机号", "姓名", "入职日期", "转正日期", "工号"],
          //数据
          data: [],
          //导出文件名称
          filename: "员工批量导入模板",
        });
      });
    },
    //复杂导出
    exportHardExcel() {},

    //点击角色按钮
    async roleClick(id) {
      this.currentId = id;
      //显示弹出框
      this.isShowRole = true;
      //将id传给子组件

      await this.$refs.roleSet.userPhoto(id);
    },
  },
  filters: {
    hireTypeVal(val) {
      let list = constant.hireType.filter((item) => item.id == val);
      return list[0] ? list[0].value : "";
    },
  },
};
</script>

<style lang='scss'>
.employees {
  padding: 20px;
  .box-cardBottom {
    margin-top: 20px;
    .has-gutter {
      background: #ccc;
    }
  }
  .el-pagination {
    text-align: right;
  }
}
</style>